package com.ali.ttt.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Author : yuxl
 * @create 2024/8/1 3:47 PM
 */
@Slf4j
@RestController
@RequestMapping("/api/future")
@Api(tags = "线程回调")
@AllArgsConstructor
public class FutureController {

    @GetMapping("/allTask")
    @ApiOperation(value = "同时进行多个任务")
    public Integer allTask() throws ExecutionException, InterruptedException {
        FutureTask<Integer> task1 = new FutureTask<>(() -> {
            int n = 1;
            for (int i = 0; i < 2; i++) {
                TimeUnit.SECONDS.sleep(1);
                n++;
            }
            return n;
        });
        FutureTask<Integer> task2 = new FutureTask<>(() -> {
            int n = 1;
            for (int i = 0; i < 3; i++) {
                TimeUnit.SECONDS.sleep(1);
                n++;
            }
            return n;
        });
        FutureTask<Integer> task3 = new FutureTask<>(() -> {
            int n = 1;
            for (int i = 0; i < 4; i++) {
                TimeUnit.SECONDS.sleep(1);
                n++;
            }
            return n;
        });
        new Thread(task1).start();
        new Thread(task2).start();
        new Thread(task3).start();
        return task1.get()+task2.get()+task3.get();
    }


}
